
import { Icon } from '../components';
import { dom } from '../tool';

interface PropsType {
    target?: HTMLElement;
    value?: 'left' | 'center' | 'right' | null;
    onChange: (value: 'left' | 'center' | 'right' | null) => void;
}

interface TextAlignType {
    new(props?: PropsType): TextAlignType;
    value: 'left' | 'center' | 'right' | null;
    onChange: (value: 'left' | 'center' | 'right' | null) => void;
    setValue: (value: 'left' | 'center' | 'right' | null) => void;
}

function TextAlign(this: TextAlignType, props?: PropsType) {
    const { target, value: defaultValue = 'left', onChange } = props || {};
    this.value = defaultValue;
    let left: any;
    let center: any;
    let right: any;
    const children = dom('div', { style: 'display: inline-block; padding: 4px 0;' });
    const container = dom('div', {
        className: 'gkh-form-item',
        target,
        childs: [dom('label', { innerText: '对齐方式' }), children]
    })
    const change = (type: any, arg: boolean, hasChange?: boolean) => {
        left.setActive(false);
        center.setActive(false);
        right.setActive(false);
        if (type === 'left') {
            left.setActive(arg);
            if (arg) {
                this.value = 'left';
            } else {
                this.value = null;
            }
        } else if (type === 'center') {
            center.setActive(arg);
            if (arg) {
                this.value = 'center';
            } else {
                this.value = null;
            }
        } else if (type === 'right') {
            right.setActive(arg);
            if (arg) {
                this.value = 'right';
            } else {
                this.value = null;
            }
        }
        if (onChange instanceof Function && !hasChange) {
            onChange(this.value);
        }
    }
    left = new Icon({
        type: 'AlignLeftIcon',
        onClick: () => {
            change("left", !left.active);
        },
        style: 'margin-right: 4px;'
    })
    center = new Icon({
        type: 'AlignCenterIcon',
        onClick: () => {
            change("center", !center.active);
        },
        style: 'margin-right: 4px;'
    })
    right = new Icon({
        type: 'AlignRightIcon',
        onClick: () => {
            change("right", !right.active);
        }
    })
    left.render(children);
    center.render(children);
    right.render(children);

    this.setValue = (arg) => {
        if (arg && "left,conter,right".indexOf(arg) < 0) {
            this.value = null;
        }
        change(arg, true, true);
    }
    this.setValue(defaultValue);
    return this;
}

export default TextAlign as unknown as TextAlignType;